package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.SeckillVoucher;
import com.hmdp.entity.VoucherOrder;
import com.hmdp.mapper.VoucherOrderMapper;
import com.hmdp.service.ISeckillVoucherService;
import com.hmdp.service.IVoucherOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisIdWorker;
import com.hmdp.utils.SimpleRedisLock;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.aop.framework.AopContext;
import org.springframework.aop.framework.AopProxy;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.connection.stream.*;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.annotation.Resource;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Slf4j
@Service
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {

    private static final DefaultRedisScript<Long> SECKILL_SCRIPT;

    static {
        SECKILL_SCRIPT = new DefaultRedisScript<>();
        SECKILL_SCRIPT.setLocation(new ClassPathResource("seckill.lua"));
        // SECKILL_SCRIPT.setLocation(new ClassPathResource("seckill_stream.lua"));
        SECKILL_SCRIPT.setResultType(Long.class);
    }

    private IVoucherOrderService proxy;
    @Resource
    private ISeckillVoucherService seckillVoucherService;
    @Resource
    private RedisIdWorker redisIdWorker;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private RedissonClient redissonClient;

    private BlockingQueue<VoucherOrder> blockingQueue = new ArrayBlockingQueue<>(1024 * 1024);
    private ExecutorService executor = Executors.newSingleThreadExecutor();

    @PostConstruct
    public void init() {
        executor.submit(new VoucherOrderTask());
    }

    // 获取消息队列中的订单信息
    /*private class VoucherOrderTask implements Runnable {
        @Override
        public void run() {
            while (true) {
                try {
                    // 1. 获取消息队列中的订单信息 XREADGROUP GROUP g1 c1 COUNT 1 BLOCK 2000 STREAMS stream.orders >
                    List<MapRecord<String, Object, Object>> list = stringRedisTemplate.opsForStream().read(
                            Consumer.from("g1", "c1"),
                            StreamReadOptions.empty().count(1).block(Duration.ofSeconds(2)),
                            StreamOffset.create("stream.orders", ReadOffset.lastConsumed())
                    );
                    // 2. 判断消息获取是否成功
                    if (list == null || list.isEmpty()) {
                        // 如果为null，说明没有消息，继续下一次循环
                        continue;
                    }

                    // 3. 解析消息中的数据
                    MapRecord<String, Object, Object> record = list.get(0);
                    Map<Object, Object> values = record.getValue();

                    // 3. 创建订单
                    VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(values, new VoucherOrder(), true);
                    // 4. 处理订单
                    handleVoucherOrder(voucherOrder);

                    // 5. 返回ACK确认 SACK stream.orders g1 id
                    stringRedisTemplate.opsForStream().acknowledge("stream.orders", "g1", record.getId());
                } catch (Exception e) {
                    log.error("处理订单异常", e);
                    handlePendingList();
                }
            }
        }

        private void handlePendingList() {
            while (true) {
                try {
                    List<MapRecord<String, Object, Object>> list = stringRedisTemplate.opsForStream().read(
                            Consumer.from("g1", "c1"),
                            StreamReadOptions.empty().count(1),
                            StreamOffset.create("stream.orders", ReadOffset.from("0"))
                    );
                    // 2. 获取消息
                    if (list == null || list.isEmpty()) {
                        break;
                    }
                    // 3. 解析消息
                    MapRecord<String, Object, Object> record = list.get(0);
                    Map<Object, Object> values = record.getValue();
                    VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(values, new VoucherOrder(), true);
                    // 4. 创建订单
                    handleVoucherOrder(voucherOrder);
                    // 5. 确认消息
                    stringRedisTemplate.opsForStream().acknowledge("stream.orders", "g1", record.getId());
                } catch (Exception e) {
                    log.error("处理pending-list异常", e);
                    try {
                        Thread.sleep(20);
                    } catch (InterruptedException ex) {
                        throw new RuntimeException(ex);
                    }
                }
            }
        }
    }*/

    /**
     * 异常信息：
     * ExecutorService（executor）在应用程序关闭时未被正确终止，
     * 导致VoucherOrderTask线程在Redis连接池关闭后继续运行。
     * @param voucherOrder
     */

    // 创建线程任务，获取阻塞队列中的订单信息
    private class VoucherOrderTask implements Runnable {
        @Override
        public void run() {
            while (true) {
                try {
                    // 获取队列中的订单信息
                    VoucherOrder voucherOrder = blockingQueue.take();
                    // 创建订单
                    handleVoucherOrder(voucherOrder);
                } catch (Exception e) {
                    log.error("处理订单异常", e);
                }
            }
        }
    }

    public void handleVoucherOrder(VoucherOrder voucherOrder) {
        try {
            log.info("开始处理订单：{}", voucherOrder.getId());
            proxy.createAsycnVoucherOrder(voucherOrder);
            log.info("订单处理成功：{}", voucherOrder.getId());
        } catch (Exception e) {
            log.error("订单处理失败：{}", voucherOrder.getId(), e);
            // 考虑重试机制或者回滚 Redis 数据
        }
    }

    /*@Override
    public Result seckillVoucher(Long voucherId) {
        // 1. 执行lua脚本
        Long userId = UserHolder.getUser().getId();
        // 获取订单 id
        Long orderId = redisIdWorker.nextId("order");
        Long result = stringRedisTemplate.execute(
                SECKILL_SCRIPT,
                Collections.emptyList(),
                voucherId.toString(),
                userId.toString(),
                orderId.toString()
        );

        // 2. 判断结果是否为0
        int r = result.intValue();

        // 2.1. 不为0，没有购买资格
        if (r != 0) {
            // 0-成功，1-失败
            return Result.fail(r == 1 ? "库存不足" : "不能重复下单");
        }

        // 前面的操作都是主线程做的，现在是子线程无法从ThreadLocal中获取，只能提前获取代理对象
        proxy = (IVoucherOrderService) AopContext.currentProxy();

        // 4. 返回订单id
        return Result.ok(orderId);
    }*/


    @Override
    //异步创建订单
    public Result seckillVoucher(Long voucherId) {
        // 1. 执行lua脚本
        Long userId = UserHolder.getUser().getId();
        Long result = stringRedisTemplate.execute(
                SECKILL_SCRIPT,
                Collections.emptyList(),
                voucherId.toString(),
                userId.toString()
        );

        // 2. 判断结果是否为0
        int r = result.intValue();

        // 2.1. 不为0，没有购买资格
        if (r != 0) {
            // 0-成功，1-失败
            return Result.fail(r == 1 ? "库存不足" : "不能重复下单");
        }

        // 2.2 为0，把下单信息保存到阻塞队列中
        long orderId = redisIdWorker.nextId("order");
        VoucherOrder voucherOrder = new VoucherOrder();
        voucherOrder.setId(orderId);
        voucherOrder.setUserId(userId);
        voucherOrder.setVoucherId(voucherId);

        // 前面的操作都是主线程做的，现在是子线程无法从ThreadLocal中获取，只能提前获取代理对象
        proxy = (IVoucherOrderService) AopContext.currentProxy();

        // 3. 放入阻塞队列中
        blockingQueue.add(voucherOrder);

        // 4. 返回订单id
        return Result.ok(orderId);
    }

    @Override
    public void createAsycnVoucherOrder(VoucherOrder voucherOrder) {
        // 5. 一人一单
        Long userId = voucherOrder.getUserId();

        long count = query().eq("user_id", userId).eq("voucher_id", voucherOrder.getVoucherId()).count();
        if (count > 0) {
            // 用户已经购买过
            log.error("用户已经购买过！");
            return;
        }

        // 6. 扣减库存，用乐观锁保证线程安全，防止超卖
        boolean success = seckillVoucherService.update()
                .setSql("stock = stock - 1")
                .eq("voucher_id", voucherOrder.getVoucherId())
                // .eq("stock", voucher.getStock()) // 这样的话太小心了，库存卖不完
                .gt("stock", 0) // 只需要判断库存是否大于0
                .update();
        if (!success) {
            // 扣减库存失败
            log.error("库存不足！");
            return;
        }

        // 7. 创建订单已经提前做好了
        save(voucherOrder);
    }
    /*@Override
    public Result seckillVoucher(Long voucherId) {
        // 1. 查询优惠券
        SeckillVoucher voucher = seckillVoucherService.getById(voucherId);

        // 2. 判断秒杀是否开始
        if (voucher.getBeginTime().isAfter(LocalDateTime.now())) {
            // 尚未开始
            return Result.fail("秒杀尚未开始！");
        }

        // 3. 判断秒杀是否结束
        if (voucher.getEndTime().isBefore(LocalDateTime.now())) {
            // 秒杀已经结束
            return Result.fail("秒杀已经结束！");
        }

        // 4. 判断库存是否充足
        if (voucher.getStock() < 1) {
            // 库存不足
            return Result.fail("库存不足！");
        }

        Long userId = UserHolder.getUser().getId();
        // 锁的粒度，越细越快，用intern()方法返回字符串常量池中已有的对象
        // 将锁加在方法体外，先提交事务再释放锁；如果锁加在方法体内，则先释放锁再提交事务，则可能发现线程安全问题
        *//* JVM级别的锁
        synchronized (userId.toString().intern()) {
            // 获取事务代理对象，是接口类型因为AOP底层是使用jdk的动态代理
            IVoucherOrderService proxyIv = (IVoucherOrderService) AopContext.currentProxy();
            // 用代理对象执行方法，防止事务失效
            return proxyIv.createVoucherOrder(voucherId);
        }*//*

        // 分布式锁
        String name = "order:" + userId;
        *//* setnx + expire + lua脚本实现的自定义锁
        SimpleRedisLock redisLock = new SimpleRedisLock(name, stringRedisTemplate);*//*

        // Redission实现的分布式锁
        RLock redisLock = redissonClient.getLock("lock:" + name);
        // 获取锁
        boolean isLock = redisLock.tryLock(); // 无参，获取锁失败不重试
        if (!isLock) {·
            // 获取锁失败，返回错误或者重试
            return Result.fail("不允许重复下单！");
        }
        try {
            IVoucherOrderService proxyIv = (IVoucherOrderService) AopContext.currentProxy();
            return proxyIv.createVoucherOrder(voucherId);
        } finally {
            // 释放锁
            redisLock.unlock();
        }

    }*/

    // 用悲观锁保证线程安全
    @Override
    @Transactional
    public Result createVoucherOrder(Long voucherId) {
        // 5. 一人一单
        Long userId = UserHolder.getUser().getId();

        long count = query().eq("user_id", userId).eq("voucher_id", voucherId).count();
        if (count > 0) {
            // 用户已经购买过
            return Result.fail("用户已经购买过！");
        }

        // 6. 扣减库存，用乐观锁保证线程安全，防止超卖
        boolean success = seckillVoucherService.update()
                .setSql("stock = stock - 1")
                .eq("voucher_id", voucherId)
                // .eq("stock", voucher.getStock()) // 这样的话太小心了，库存卖不完
                .gt("stock", 0) // 只需要判断库存是否大于0
                .update();
        if (!success) {
            // 扣减库存失败
            return Result.fail("库存不足！");
        }

        // 7. 创建订单
        VoucherOrder voucherOrder = new VoucherOrder();
        // 生成订单号
        long orderId = redisIdWorker.nextId("order");
        voucherOrder.setId(orderId);
        // 用户id
        UserDTO user = UserHolder.getUser();
        voucherOrder.setUserId(user.getId());
        // 代金券id
        voucherOrder.setVoucherId(voucherId);
        save(voucherOrder);

        return Result.ok(orderId);
    }


}
